package com.luyue.zagj.receiver;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Config;
import android.util.Log;

import com.luyue.zagj.activity.home.VehicleInfoActivity;
import com.luyue.zagj.utils.SPutils;

/**
 * Created by Chen qin lang on 2016/12/20.
 * 邮箱 :   619766577@qq.com
 */
public class PhoneStateReceive extends BroadcastReceiver {
    private int mCurrentState = TelephonyManager.CALL_STATE_IDLE;
    private int mOldState = TelephonyManager.CALL_STATE_IDLE;

    private Context mContext;

    @Override
    public void onReceive(Context context, Intent intent) {
        mContext = context;
        if (intent.getAction().equals("android.intent.action.PHONE_STATE")) {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
            tm.listen(new MyPhoneStateListener(), PhoneStateListener.LISTEN_CALL_STATE);
        }
    }

    private class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            mOldState = (int) SPutils.get(mContext, "mOldState", mOldState);

            switch (state) {
                case TelephonyManager.CALL_STATE_IDLE:
                    mCurrentState = TelephonyManager.CALL_STATE_IDLE;
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK:
                    mCurrentState = TelephonyManager.CALL_STATE_OFFHOOK;
                    break;
                case TelephonyManager.CALL_STATE_RINGING:
                    mCurrentState = TelephonyManager.CALL_STATE_RINGING;
                    break;
            }

            if (mOldState == TelephonyManager.CALL_STATE_IDLE &&
                    mCurrentState == TelephonyManager.CALL_STATE_OFFHOOK) {
                Log.i("receiver", "onCallStateChanged: 接通");
                SPutils.put(mContext, "mCurrentState", mCurrentState);

            } else if (mOldState == TelephonyManager.CALL_STATE_OFFHOOK &&
                    mCurrentState == TelephonyManager.CALL_STATE_IDLE) {
                Log.i("receiver", "onCallStateChanged: 挂断");
                SPutils.put(mContext, "mCurrentState", mCurrentState);
                Intent intent = new Intent(mContext, VehicleInfoActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }
        }
    }
}